package com.xinhua.web.servlet;

import com.xinhua.domain.Consumption;
import com.xinhua.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

//添加
@WebServlet("/inserServlet")
public class InserServlet extends HttpServlet {
    private QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> parameterMap = request.getParameterMap();
        int uuid = (int) request.getSession().getAttribute("uuid");
        Consumption user = new Consumption();
        user.setName(request.getParameter("name"));
        user.setPrice(Integer.parseInt(request.getParameter("price")));
        user.setType(request.getParameter("type"));
        user.setTime(request.getParameter("time"));
        try {
            String sql = "insert into day23.consumption values(null,?,?,?,?,?)";
            queryRunner.update(sql, user.getName(), user.getPrice(), user.getType(), user.getTime(),uuid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        response.sendRedirect(request.getContextPath() + "/findServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
